package controller;

import dao.GoodsDao;
import domain.Goods;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import util.JsonResult;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/goods")
public class GoodsController {
    @Resource
    private GoodsDao goodsDao;

    private JsonResult jsonResult= new JsonResult();

    /*根据id查询goods*/
    @RequestMapping(value = "/show")
    @ResponseBody
    @Transactional
    public Goods show(@RequestBody Map<String, Object> map) {

        Goods goods = goodsDao.selectById((Integer) map.get("id"));
        return goods;
    }

    /*插入商品*/
    @RequestMapping(value = "/insertGoods")
    @ResponseBody
    @Transactional
    public JsonResult insertGoods(@RequestBody Map<String, Goods> map) {
        int flag = goodsDao.insert(map.get("goods"));
        if (flag > 0) {
            jsonResult.setResult("true");
            return jsonResult;
        } else {
            jsonResult.setResult("false");
            return jsonResult;
        }
    }

    /*修改商品*/
    @RequestMapping(value = "/updateGoods")
    @ResponseBody
    @Transactional
    public JsonResult updateGoods(@RequestBody Map<String, Goods> map) {
        int flag = goodsDao.update(map.get("goods"));
        if (flag == 0) {
            jsonResult.setResult("false");
            return jsonResult;
        } else {
            jsonResult.setResult("true");
            return jsonResult;
        }
    }

    /*删除商品*/
    @RequestMapping(value = "/deleteGoods")
    @ResponseBody
    @Transactional
    public JsonResult deleteGoods(@RequestBody Map<String, Object> map) {
        int flag = goodsDao.delete((Integer) map.get("id"));
        if (flag == 0) {
            jsonResult.setResult("false");
            return jsonResult;
        } else {
            jsonResult.setResult("true");
            return jsonResult;
        }
    }

    /*查询所有商品*/
    @RequestMapping(value = "/showAll")
    @ResponseBody
    @Transactional
    public List<Goods> showAll() {
        List<Goods> goods = new ArrayList<Goods>();
        goods = goodsDao.selectAll();
        return goods;
    }


}



